package com.xhx.accounting.ui.home;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.xhx.accounting.DBDao;
import com.xhx.accounting.Keyboard;
import com.xhx.accounting.MainActivity;
import com.xhx.accounting.R;
import com.xhx.accounting.RackMonthPicker;
import com.xhx.accounting.accountbook;
import com.xhx.accounting.databinding.FragmentHomeBinding;
import com.xhx.accounting.search;

import listener.DateMonthDialogListener;
import listener.OnCancelMonthDialogListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private DBDao db;
    protected RecyclerView mRecyclerView;
    protected RecyclerView.LayoutManager mLayoutManager;
    private TextView cost;
    private TextView income;
    private TextView dateChange;
    private Map<String,Object> record;
    private enum LayoutManagerType {
        GRID_LAYOUT_MANAGER,
        LINEAR_LAYOUT_MANAGER
    }

    private Long startTime, endTime;
    protected LayoutManagerType mCurrentLayoutManagerType;
    protected CustomAdapter mAdapter;
    protected List<Map<String, Object>> mDataset;
    private static final String KEY_LAYOUT_MANAGER = "layoutManager";
    public int currentAccountBook;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        db = new DBDao(getActivity());
        currentAccountBook = db.getCurrentAccountBook();

        //initData
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0); //获取当前月第一天
        c.set(Calendar.DAY_OF_MONTH, 1); //设置为1号,当前日期既为本月第一天
        c.set(Calendar.HOUR_OF_DAY, 0); //将小时至0
        c.set(Calendar.MINUTE, 0); //将分钟至0
        c.set(Calendar.SECOND,0); //将秒至0
        c.set(Calendar.MILLISECOND, 0); //将毫秒至0
        startTime = c.getTimeInMillis()/1000;
        Calendar c2 = Calendar.getInstance();
        c2.set(Calendar.DAY_OF_MONTH, c2.getActualMaximum(Calendar.DAY_OF_MONTH)); //获取当前月最后一天
        c2.set(Calendar.HOUR_OF_DAY, 23); //将小时至23
        c2.set(Calendar.MINUTE, 59); //将分钟至59
        c2.set(Calendar.SECOND,59); //将秒至59
        c2.set(Calendar.MILLISECOND, 999); //将毫秒至999
        endTime = c2.getTimeInMillis()/1000;
        String year = String.valueOf(c.get(Calendar.YEAR));
        String month = String.valueOf(c.get(Calendar.MONTH) + 1);
        //
        record = db.getRecord2(startTime, endTime, currentAccountBook);
        mDataset = new ArrayList<>();
        mDataset.addAll((List)record.get("result"));

        int x = db.getBudget();
        double y = db.getRecord3(startTime,endTime);
        double z = Double.valueOf(x) - y;
        Log.d("xxx",String.valueOf(z));
        if(z<=0){
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity());
            builder.setMessage("本月已超支，请合理规划");
            builder.setPositiveButton("确认", (dialog, id1) -> {

            });
            builder.show();
        }

        //组件init
        cost = root.findViewById(R.id.cost);
        income = root.findViewById(R.id.income);
        mRecyclerView = root.findViewById(R.id.date_list);
        dateChange = root.findViewById(R.id.text_home);
        ImageView fab1 = root.findViewById(R.id.add_main);


        //顶部数据
        cost.setText(String.valueOf(record.get("cost_sum")));
        income.setText(String.valueOf(record.get("income_sum")));
        dateChange.setText(year + "年" + month +"月");

        //recycleView
        mLayoutManager = new LinearLayoutManager(getActivity());
        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.scrollToPosition(0);
        mAdapter = new CustomAdapter(mDataset);

        mRecyclerView.setAdapter(mAdapter);

        //按钮监听
        ImageView fab = root.findViewById(R.id.btn_account_book);
        fab.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setClass(getActivity(), accountbook.class);
            startActivity(intent);
        });

        fab1.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setClass(getActivity(), Keyboard.class);
            intent.putExtra("accountId",String.valueOf(currentAccountBook));
            startActivity(intent);
        });

        ImageView fab2 = root.findViewById(R.id.btn_search);
        fab2.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setClass(getActivity(), search.class);
            intent.putExtra("accountId",currentAccountBook);
            startActivity(intent);
        });

        dateChange.setOnClickListener(v -> {
            new RackMonthPicker(getActivity())
                    .setLocale(Locale.CHINESE)
                    .setNegativeText("取消")
                    .setPositiveText("确定")
                    .setPositiveButton(new DateMonthDialogListener() {
                        @Override
                        public void onDateMonth(int month, int startDate, int endDate, int year, String monthLabel) throws ParseException {
                            Log.d("year",String.valueOf(year));
                            Log.d("month",String.valueOf(month));
                            Log.d("startDate",String.valueOf(startDate));
                            Log.d("endDate",String.valueOf(endDate));
                            dateChange.setText(year + "年" + month +"月");
                            Long startDateTimestamp;
                            Long endDateTimestamp;

                            String start = year + "-" + month + "-" + startDate;
                            String end = year + "-" + month + "-" + endDate;
                            //
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Date date1 = simpleDateFormat.parse(start);
                            Date date2 = simpleDateFormat.parse(end);
                            startDateTimestamp = date1.getTime()/1000;
                            endDateTimestamp = date2.getTime()/1000;
                            Log.d("start",String.valueOf(startDateTimestamp));
                            Log.d("end",String.valueOf(endDateTimestamp));
                            startTime = startDateTimestamp;
                            endTime = endDateTimestamp;
                            //
                            refresh();
                        }
                    })
                    .setNegativeButton(new OnCancelMonthDialogListener() {
                        @Override
                        public void onCancel(AlertDialog dialog) {
                        }
                    }).show();
        });
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }


    //从添加回来后执行
    @Override
    public void onStart() {
        super.onStart();
        refresh();
        Log.d("currentbook",String.valueOf(currentAccountBook));
    }

    //刷新列表
    public void refresh() {
        //recycleView 刷新
        currentAccountBook = db.getCurrentAccountBook();
        Log.d("fragmentaccountbook",String.valueOf(currentAccountBook));
        record.clear();
        record = db.getRecord2(startTime, endTime, currentAccountBook);
        mDataset.clear();
        mDataset.addAll((List)record.get("result"));
        mAdapter.notifyDataSetChanged();
        //顶部数据刷新
        cost.setText(String.valueOf(record.get("cost_sum")));
        income.setText(String.valueOf(record.get("income_sum")));
    }
}